<?php

// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: PHP@妖孽 <dino_ma@163.com>
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
 * 商城
 +------------------------------------------------------------------------------
 * @version   1.0
 * @since 2015-11-19
 +------------------------------------------------------------------------------
 */
namespace Home\Controller;
use Think\Controller;


class ShopController extends HomeController {
	
	/**
	 * @todo 定义天天特卖状态常量
	 * @author Crusie<jiangyu@hrbjjhh.com> 
	 */
	private static  $state_1_map = array(
			0 => '未开始',
			1 => '',
			2 => '已结束',
			3 => '已售罄'
	);//图片蒙层显示状态
	private static  $state_2_map = array(
			0 => '抢先看',
			1 => '立即购买',
			2 => '已结束',
			3 => '已售罄'
	);//pc按钮显示状态
	private static  $buy_state_map = array(
			0 => '即将开始',
			1 => '立即购买',
			2 => '已结束',
			3 => '已售罄'
	);//mobile详情页按钮显示状态
    /**
     * @todo 初始化
     * @since 2015-12-3
     * @author sap
     */
    public function _initialize(){
        parent::_initialize();
        //必须为手机端查看的页面
        $mobile_arr = array('goodsGroup','goodsGroupInfo','goodsGroupOpen','goodsGroupIn','goodsGroupBuy');
        if(in_array_case(ACTION_NAME, $mobile_arr)){
            if(!isMobile()){
                $this->error('请用移动端查看');
            }
        }
        //非登录状态下不允许访问的页面
        $arr = array('goodsGroupOpen','goodsGroupIn','goodsGroupBuy','buy','pay');
        if(in_array_case(ACTION_NAME, $arr)){
            if(!is_login()){
                $this->error('请登陆',U('Customer/login'));
            }
        }
    }
    
    /**
     * @todo 团购首页
     * @author sap
     * @since 2015-12-10
     */
    public function goodsGroup(){
        $this->meta_title = '一起来开团吧！';
        $this->display('goods_group');
    }
    
    /**
     * @todo 团购列表
     * @author sap
     * @since 2015-11-30
     */
    public function goodsGroupList(){
        $p = (int)I('p')==0?1:(int)I('p');
        $map = array();//查询条件初始化
        $map['status'] = 1;//商品上架
        $map['goods_type'] = 2;//团购商品
        $obj = D('Admin/ShopGroupView');
        $count = $obj->where($map)->count();//团购产品总数
        $list = array();
        if($count > 0){
            $page = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;//每页显示的记录数(10)
            $list=$obj->where($map)->field('shop_group_id,goods_id,shop_group_price,shop_group_pic_id,market_price,goods_name,goods_introduction')->order('goods_id')->page($p,$page)->select();
        
            $obj_shop_group = D('ShopGroup');
            $list = $obj_shop_group->handleShopList($list);//列表数据处理，添加参团人数等字段
            if(empty($list)){
                $this->error($obj_shop_group->getError());
            }
        }
        
        $call_back = array();
        if(empty($list)){
            $call_back['status'] = 0;
        }else{
            $call_back['status'] = 1;
        }
        $call_back['data'] = $list;
        $this->ajaxReturn($call_back);
    }
    
    /**
     * @todo 团购详细页
     * @author sap
     * @since 2015-12-1
     */
    public function goodsGroupInfo(){
        $obj_shop_group = D('ShopGroup');
        $info = $obj_shop_group->shopGroupInfo();
        if(empty($info)){
            $this->error($obj_shop_group->getError());
        }
        $this->assign('list',$info);
        $this->meta_title = '一起来开团吧！';
        $this->display('goods_groupinfo');
    }

    /**
     * @todo 我要开团
     * @author sap
     * @since 2015-12-2
     */
    public function goodsGroupOpen(){
        $goods_id = (int)I('goods_id');
        $obj_shop_group = D('ShopGroup');
        $team_id = $obj_shop_group->goodsGroupOpen();
        if(empty($team_id)){
            $this->error($obj_shop_group->getError());
        }
        $this->success('开团成功',U('Shop/goodsGroupInfo',array('goods_id'=>$goods_id,'team_id'=>$team_id)));
    }
    
    /**
     * @todo 我要入团
     * @author sap
     * @since 2015-12-2
     */
    public function goodsGroupIn(){
        $obj_shop_group = D('ShopGroup');
        $team_id = $obj_shop_group->goodsGroupIn();
        if(empty($team_id)){
            $this->error($obj_shop_group->getError());
        }
        $this->success('入团成功');
    }
    
    /**
     * @todo 购买
     * @author sap
     * @since 2015-12-3
     */
    public function goodsGroupBuy(){
        $obj_shop_group = D('ShopGroup');
        $order_id = $obj_shop_group->goodsGroupBuy();
        if(empty($order_id)){
            $this->error($obj_shop_group->getError());
        }
        $this->success('购买成功',U('Shop/pay',array('id'=>$order_id)));
    }
    
    /**
     * 天天特卖
     * @todo  天天特卖首页(新)
     * @author Crusie<jiangyu@hrbjjhh.com>
     */
    public function sale(){
    	$is_mobile = isMobile();
    	$obj = D('Shop');
    	$goods_list = array();
    	//a 每日爆款  b 明日预告
    	if($is_mobile){
    		$goods_list['a'] = $obj->getGoodsList(array('position' => 1,'status' => 1),16,$is_mobile,140,140);//PC获取爆款数据
    		$goods_list['b'] = $obj->getGoodsList(array('position' => 4096,'status' => 1),16,$is_mobile,140,140);
    	}else{
    		$goods_list['a'] = $obj->getGoodsList(array('position' => 1,'status' => 1),16,$is_mobile,460,280);//PC获取爆款数据
    		$goods_list['b'] = $obj->getGoodsList(array('position' => 4096,'status' => 1),16,$is_mobile,460,280);
    	}
    	$classify_data = $obj->getClassify();//分类信息
    	$countdown = $obj->everyDayTen();
    	$template = $is_mobile ? 'Shop/mobile/sale' : 'Shop/sale';
    	$this->assign('goods_list',json_encode($goods_list));
    	$this->assign('classify_data',json_encode($classify_data));
    	$this->assign('countdown',$countdown);
    	$this->assign('state_1_map',json_encode(self::$state_1_map));
    	$this->assign('state_2_map',json_encode(self::$state_2_map));
    	$this->assign('meta_title','天天特卖');
    	$this->display($template);
    }
    
    /**
     * 天天特卖
     * @todo 天天特卖首页推荐商品接口
     * @param array    $map  		条件
     * @param int      $page 		页码
     * @param int      $page_count  每页条数
     * @param string   $field 		需要查询的字段
     * @param string   $order 		排序
     * @author Crusie <jiangyu@hrbjjhh.com>
     */
    public function recommendList(){
    	$category_id = (int)I('get.category');
    	$page = (int)I('get.p')==0 ? 1 : (int)I('get.p');
    	$obj = D('Shop');
    	switch ($category_id){
    	    case 0:
    	        $category = D('Admin/ServiceApi')->getSalePositionList(32,2048);
    	        $category_new = empty($category) ? array() : array_keys($category);
    	        $map['position'] = $category_new;
    	        break;
    	    case -1:
    	        $category = D('Admin/ServiceApi')->getSalePositionList(16384,1048576);
    	        $category_new = empty($category) ? array() : array_keys($category);
    	        $map['position'] = $category_new;
    	        break;
    	    default:
    	        $map['position'] = $category_id;
    	}
    	
    	$map['status'] = 1;
    	$is_mobile = isMobile();
    	$call_back = $is_mobile ? $obj->saleRecommendList($map,$page,10,$is_mobile,200,200) : $obj->saleRecommendList($map,$page,40,$is_mobile,226,226);
    	$this->ajaxReturn($call_back);
    }
    
    /**
     * 天天特卖
     * @todo  天天特卖品牌店铺页
     * @author Crusie<jiangyu@hrbjjhh.com>
     */
    public function brand(){
    	$id = (int)I('get.id');//接到shop_id
    	if(0 === $id){
    		$this->error('店铺参数错误');
    	}
    	$obj = D('Shop');
    	$is_mobile = isMobile();
    	$shop_data = $is_mobile ? $obj->getSaleBrand($id,$is_mobile,414,99) : $obj->getSaleBrand($id,$is_mobile,960,230);//获取店铺信息
    	if($shop_data === false) {
    		$this->error($obj->getError());
    	}
    	if(empty($shop_data)){
    		$this->error('暂无店铺！');
    	}
    	if($is_mobile){
    		$template = 'Shop/mobile/brandDetail';
    		$this->assign('shop_data',json_encode($shop_data));
    	}else{
    		$template = 'Shop/brandDetail';
    		$this->assign('shop_data',$shop_data);
    	}
    	//手机json的   pc自己渲染的
    	$this->assign('meta_title','天天特卖');
    	$this->display($template);
    }
    
    /**
     * 天天特卖
     * @todo 天天特卖店铺下商品信息接口
     * @param array    $map  		条件
     * @param int      $page 		页码
     * @param int      $page_count  每页条数
     * @author Crusie <jiangyu@hrbjjhh.com>
     */
    public function brandGoods(){
    	/* 商品促销状态，全部时建议传值负数 */
    	$type_id = (int)I('get.category');
    	$shop_id = (int)I('get.shop_id');
     	$page = (int)I('get.p')==0 ? 1 : (int)I('get.p');
     	if(0 == $shop_id){
     		$this->error('店铺参数有误！');
     	}
    	if(-1 < $type_id){
    		$map['goods_type'] = $type_id;
    	}
    	$map['shop_id'] = $shop_id;
    	$map['status'] = 1;
    	$obj = D('Shop');
    	$is_mobile = isMobile();
    	$call_back = $is_mobile ? $obj->saleRecommendList($map,$page,10,$is_mobile,226,226) : $obj->saleRecommendList($map,$page,40,$is_mobile,275,275);
    	$this->ajaxReturn($call_back);
    }
    
    /**
     * 天天特卖
     * @todo  天天特卖品牌汇集页
     * @author Crusie<jiangyu@hrbjjhh.com>
     */
    public function allBrand(){
    	$obj = D('Shop');
    	$is_mobile = isMobile();
    	if(!$is_mobile){
    		$goods_list = $obj->getGoodsList(array('position' => 8192,'status' => 1),4,$is_mobile,275,275);//推荐商品详情
    		$this->assign('goods_list',$goods_list);
    	}
    	$map['status'] = 1;
    	$shop_list = $is_mobile ? $obj->getShopList($map,130,40) : $obj->getShopList($map,159,79);
     	$template = $is_mobile ? 'Shop/mobile/brand' : 'Shop/brand';
    	$this->assign('shop_list',json_encode($shop_list));
    	$this->assign('meta_title','天天特卖');
    	$this->display($template);
    }
    
    /**
     * 天天特卖
     * @todo 商品详情
     * @author Crusie<jiangyu@hrbjjhh.com>
     */
    public function goods(){
    	$goods_id = (int)I('get.id');
    	if($goods_id == 0){
    		$this->error('id有误！');
    	}
    	$is_mobile = isMobile();
    	$obj = D('Shop');
    	//商品详情
    	$goods_data = $is_mobile ? $obj->goodsData($goods_id,$is_mobile,375,335) : $obj->goodsData($goods_id,$is_mobile);
    	if(empty($goods_data)){
    		$this->error($obj->getError());
    	}
    	if(false === $is_mobile){
    		//正常推荐商品详情
    		$recommend_data = $obj->detailRecommendList(array('position' => 1,'status' => 1),4);//推荐商品详情
    		//下架推荐商品详情
    		$recommend_status_data = ($goods_data['status'] == 2)?$obj->detailRecommendList(array('position' => 2,'status' => 1),3):null;
    		//促销情况下计算初始时间
    		$time = ($goods_data['goods_type'] == 1)?$obj->goodsTime($goods_data['promotion_start_time'],$goods_data['promotion_end_time']):null;
    		//二维码地址
    		$cur_url = U('/Shop/code',array ('text' =>base64_encode('http://'.$_SERVER['HTTP_HOST'].U('Shop/goods',array('id'=>$goods_id),true))));
    		$template = '';//PC模板
    		$this->assign('recommend_data',$recommend_data); //推荐数据
    		$this->assign('recommend_status_data',$recommend_status_data); //下架推荐数据
    		$this->assign('time',$time);
    		$this->assign('cur_url',$cur_url); //商品url 二维码地址
    		$this->assign('meta_title',$goods_data['goods_name']);
    		$this->assign('goods_data',$goods_data); //商品数据
    	}else{
    		$this->assign('buy_state_map',json_encode(self::$buy_state_map)); //商品数据
    		$this->assign('goods_data',json_encode($goods_data)); //商品数据
    		$template = 'Shop/mobile/goods';//手机模板
    	}
    	$this->display($template);
    }
    
    /**
     * 购买流程
     * @author fzh<fanzhaohai@hrbjjhh.com>
     */
    public function buy(){
        $goods_id = (int)I('id');
        if($goods_id ==0){
            $this->error('请求参数非法');
        }
        $order = D('ShopOrder');
        //神器
        $phone_list = S('sale_shopping_goods_moblie_phone_list');
        if(!empty($phone_list)){
            $arr = explode('|', $phone_list);
            if(count($arr)>0){
                foreach ($arr as $key => $val){
                    $list = explode(':', $val);
                    if(!isset($list[0]) || !is_numeric($list[0])) continue;
                    if(!isset($list[1]) || !is_numeric($list[1])) continue;
                    if($list[0] == $goods_id){
                        $order->buyGoods($goods_id,$list[1]);
                    }
                }
            }
        }
        //开始购买
        $order_id = $order->buyGoods($goods_id,UID);
        if(false === $order_id){
            $this->error($order->getError());
        }else{
            $this->redirect('Shop/pay',array('id'=>$order_id));
        }
    }
    
    /**
     * 付款页面（订单付款提交页）
     * @author fzh<fanzhaohai@hrbjjhh.com>
     *
     */
    public function pay(){
//         if(UID!=1){
//             $this->error('暂时关闭支付,请稍后再试');
//         }
        $id = (int)I('get.id');
        if($id == 0){
            $this->error('订单信息错误');
        }
        $map['order_id'] = $id;
        $map['customer_id'] = UID;
        $field = 'goods_name,goods_title,shop_price,promotion_price,goods_unit,goods_deposit,goods_type';
        $shop_order = M('OrderGoodsSnapshot')->field($field)->where($map)->find();
        
        //判断是否可以进行过支付
        $shoporder = D('ShopOrder');
        $pay_status = $shoporder->checkPay($id);
        if(false === $pay_status){
            $this->error($shoporder->getError());
        }
        $this->assign("pay_status",$pay_status);
        $this->assign("shop_order",$shop_order);
        $this->assign("meta_title",'我的订单');
        $template = isMobile() ? 'Shop/mobile/pay' : '';
        $this->display($template);
    }
    
    /**
     * 付款流程（支付操作）
     * @author fzh<fanzhaohai@hrbjjhh.com>
     *
     */
    public function payment() {
//         if(UID!=1){
//             $this->error('暂时关闭支付,请稍后再试');
//         }
        
        $id = (int)I('post.id');
        $pay_type = (string)I('post.pay_type','','htmlspecialchars');
        $open_id = (string)I('post.open_id','','htmlspecialchars');
        if($id == 0){
            $this->error('订单id错误');
        }
        $order = D('ShopOrder');
        $result = $order->pay($id,$pay_type,$open_id);
        $this->ajaxReturn($result);
    }

    /**
     * 手机端支付提交（ 选择支付方式页面）
     * @author fzh<fanzhaohai@hrbjjhh.com>
     *
     */
    public function payMethod(){
        $msj = I('msj','','htmlspecialchars');
        $id = (int)I('id');
        if($id <= 0){
            $this->error('订单信息错误。');
        }
        $map['order_id'] = $id;
        $field = 'goods_deposit';
        $shop_order = M('OrderGoodsSnapshot')->field($field)->where($map)->find();
        if(empty($shop_order)){
            $this->error('订单信息错误。');
        }
        $weixin = strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger');
        if($weixin && (!isset($msj) || $msj!=md5($id))){ //在微信端获取openid
            $order = D('ShopOrder');
            $url = $order->getOpenId($id);
            if(false === $url){
                $this->error($order->getError());
            }else{
                redirect($url);
            }
        }
        $this->assign('weixin',$weixin);
        $this->assign('shop_order',$shop_order);
        $this->assign('meta_title','付款详情');
        $this->display('Shop/mobile/payMethod');
    }
    
    /**
     * 手机端 支付宝付款页面
     * @author fzh<fanzhaohai@hrbjjhh.com>
     *
     */
    public function payAlipayTip(){
        if(false === isMobile()){
            $this->error('此页面只能在手机上访问！');
        }
        $is_user_agent = strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger'); //判断是否在微信端
        $this->assign('is_user_agent',$is_user_agent);
        $this->assign('meta_title','支付提示');
        $this->display('Shop/mobile/payAlipayTip');
    }
    
    /**
     * 返回二维码
     * @author fzh<fanzhaohai@hrbjjhh.com>
     *
     */
    public function code(){
        $text = I('get.text','','htmlspecialchars,base64_decode');
        return getQrCode($text);
    }
    
    /**
     * 支付成功页面
     * @author fzh<fanzhaohai@hrbjjhh.com>
     *
     */
    public function paySuccess(){
        $this->assign('meta_title','支付成功');
        $template = isMobile() ? 'Shop/mobile/paySuccess' : '';
        $this->display($template);
    }
    
}
